/*
 * ***** BEGIN LICENSE BLOCK *****
 * This file is part of "myWiWall".
 * Copyright (c) 2007-2008 CRP Henri Tudor and contributors.
 * All rights reserved.
 *
 * "myWiWall" is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as published by
 * the Free Software Foundation.
 * 
 * "myWiWall" is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with "myWiWall"; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * ***** END LICENSE BLOCK *****
 */


	var widgetFactory = new WidgetFactory();
	
	function WidgetFactory()
	{
		/* the widget object container */
		this.widgets = new Object();

		this.parseManifest = function(data)
		{
			try {
				var manifest = configParser.parse(data);
			} catch (e)
			{
				notify('Parsing error: ' + e);
			}
			
			widgetFactory.widgets[manifest['id']].init(manifest);
		}

		/* the main function to add new widgets */
		this.requestManifest = function(widgetId, options)
		{
			if (this.widgets[widgetId])
			{
				alert(I18n.__("The Widget is already loaded") + '.');
			}
			else
			{
				// !!!
				// For dev : Here you can inject some data in the widget container !!!!!!
				// !!!
				this.widgets[widgetId] = new WidgetContainer(widgetId);
				var widget = this.widgets[widgetId];
				
				widget.minimized = (options && options['minimized'] == 1) ? true : false;
				widget.requiresSync = (options && options['requiresSync']);
				
				if (options && options['col'])
					$('#' + options['col']).prepend(widget.displayPlaceHolder());
				else
					$('#c_0').prepend(widget.displayPlaceHolder());
					
				try {
					$.ajax({
						dataType: 'xml',
						success: widgetFactory.parseManifest,
						error: function() {widgetFactory.requestManifestFailed(widgetId);},
						type: 'GET',
						url: '../../index.php/engine/getManifest?widget=' + widgetId
					});
				} catch (e)
				{
					debug(e);
					widgetFactory.requestManifestFailed(widgetId);
				}
			}
		}
		
		/* recover from an error in the widget initialization process */
		this.requestManifestFailed = function(widgetId)
		{
			debug('requestManifestFailed');
			
			/* delete the widget DOM */
			$('#widgetContainer_' + widgetId).remove();
			
			/* delete the widget object */
			delete widgetFactory.widgets[widgetId];
		}
	}